<!-- 展示这个admin的一个list的一个属性,在这个地方 -->
<template>
  <div>
    <!-- 面包屑导航 -->

    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/userManage' }"
        >用户管理</el-breadcrumb-item
      >
    </el-breadcrumb>

    <el-card>
      <!-- 搜索区域 -->

      <el-row>
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button type="warning" @click="handleAddMoreUser"
            >批量添加用户</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button type="success" @click="handleAddMoreUser"
            >批量删除用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 border边框 stripe就是随行变色-->
      <el-table :data="userLists" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="密码" prop="password"></el-table-column>
        <el-table-column label="电话" prop="phoneNumber"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="学院" prop="collage"></el-table-column>
        <el-table-column width="50px" label="性别" prop="sex" style=""></el-table-column>
        <!-- 用户的状态 -->
        <el-table-column width="70px" label="状态" prop="enable">
          <template slot-scope="scope">
            <!-- scope.row 每一行的数据，然后进行之后的操作按钮，进行之后的操作 -->
            <el-switch
              v-model="scope.row.enable"
              @change="onChangeUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.phoneNumber)"
            ></el-button>
            <el-button
              type="success"
              icon="el-icon-user"
              size="mini"
              @click="editUserAuthorDialog(scope.row.phoneNumber)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.phoneNumber)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 size-change每页最大变化数，current-change当前最大也变化数 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[1, 2, 5, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible="addDialogVisible"
      width="35%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="userName">
          <!-- 直接使用这个框架里面的icon -->
          <!-- <el-input
                v-model="loginForm.username"
                prefix-icon="el-icon-user-solid"
              ></el-input> -->

          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
          <!-- <el-input
                v-model="loginForm.password"
                prefix-icon="el-icon-search"
              ></el-input> -->
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
          <!-- <el-input
                v-model="loginForm.password"
                prefix-icon="el-icon-search"
              ></el-input> -->
        </el-form-item>
        <el-form-item label="电话" prop="phoneNumber">
          <el-input v-model="addForm.phoneNumber"></el-input>
          <!-- <el-input
                v-model="loginForm.password"
                prefix-icon="el-icon-search"
              ></el-input> -->
        </el-form-item>
        <el-form-item label="学院" prop="collage">
          <el-select v-model="addForm.collage" placeholder="请选择学院">
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
          <!-- <el-input
                v-model="loginForm.password"
                prefix-icon="el-icon-search"
              ></el-input> -->
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="addForm.sex" placeholder="请选择性别">
            <el-option
              v-for="item in sexOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
          <!-- <el-input
                v-model="loginForm.password"
                prefix-icon="el-icon-search"
              ></el-input> -->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户的权限"
      :visible="editUserAuthorDialogVisible"
      width="50%"
      @close="editUserAuthorDialogClose"
    >
      <el-transfer
        v-model="author"
        :data="authorData"
        :titles="['可用权限', '当前拥有权限']"
      ></el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserAuthorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserAuthor">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息的对话框 -->
    <el-dialog
      title="修改信息"
      :visible="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phoneNumber">
          <el-input v-model="editForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="collage">
          <el-select v-model="editForm.collage" placeholder="请选择学院">
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别">
            <el-option
              v-for="item in sexOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "UserList",
  data() {
    const generateData = () => {
      const data = [];

      data.push(
        {
          key: "admin",
          label: "admin",
        },
        {
          key: "user",
          label: "user",
        }
      );
      return data;
    };

    return {
      authorName: ["admin", "user"],
      author: [],
      authorid: "",
      editUserAuthorDialogVisible: false,
      authorData: generateData(),
      // 下拉选择框
      schoolOptions: [
        { value: "计科院", label: "计科院" },
        { value: "电子院", label: "电子院" },
        { value: "商英院", label: "商英院" },
        { value: "动院", label: "动院" },
        { value: "马克思院", label: "马克思院" },
      ],

      sexOptions: [
        { value: "Boy", label: "男" },
        { value: "Girl", label: "女" },
      ],
      //查询信息的一个数
      queryInfo: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 5, //每页最大数
      },
      userLists: [], //用户列表
      total: 0, //总的记录数
      addDialogVisible: false, //对话框显示的信息
      addForm: {
        userName: "",
        password: "",
        phoneNumber: "",
        email: "",
        collage: "",
        sex: "",
      },
      editForm: {
        username: "",
        password: "",
        phoneNumber: "",
        email: "",
        collage: "",
        sex: "",
      },
      editDialogVisible: false,
      addFormRules: {
        userName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 5,
            max: 11,
            message: "长度在 5 到 11 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码名称", trigger: "blur" },
          {
            min: 5,
            max: 11,
            message: "长度在 5 到 11 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "长度必须在11的位数",
            trigger: "blur",
          },
        ],
        collage: [{ required: true, message: "请选择学院", trigger: "blur" }],
        sex: [{ required: true, message: "请输入性别", trigger: "blur" }],
      },
      editFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 5,
            max: 11,
            message: "长度在 5 到 11 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码名称", trigger: "blur" },
          {
            min: 5,
            max: 11,
            message: "长度在 5 到 11 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "长度必须在11的位数",
            trigger: "blur",
          },
        ],
        collage: [{ required: true, message: "请选择学院", trigger: "blur" }],
        sex: [{ required: true, message: "请输入性别", trigger: "blur" }],
      },
    };
  },
  created() {
    //刚开始的地方进行使用的，然后就可以得到这个数据
    this.getUserList();
  },
  methods: {
    generateData() {},
    //获取所有的数据
    async getUserList() {
      const { data: res } = await this.$http.post(
        "/admin/userList?query=" +
          this.queryInfo.query +
          "&pageNum=" +
          this.queryInfo.pageNum +
          "&pageSize=" +
          this.queryInfo.pageSize
      );
      //在这个地方是不需要这个下划线的

      console.log('====================================');
      console.log(res.data);
      console.log('====================================');
      this.userLists = res.data;
      this.total = res.number;
    },
    editUserAuthorDialog(id) {
      console.log(
        "==============然后就可以进行之后的查找======================"
      );
      console.log(this.userLists);
      console.log("====================================");
      let a = "";

      for (const iterator of this.userLists) {
        if (iterator.phoneNumber == id) {
          a = iterator.authorities
            .map((obj, index) => {
              return obj.authority;
            })
            .join(",");
        }
      }
      this.author = a.split(",");
      this.authorData = [
        {
          key: "admin",
          label: "admin",
        },
        {
          key: "user",
          label: "user",
        },
      ];
      if (this.author.length == 1) {
        if (this.author[0] == "admin") {
          this.authorData[0].disabled = true;
        } else {
          this.authorData[1].disabled = true;
        }
      }
      this.authorid = id; //这个是为了便于修改赋值权限的修改部分
      this.editUserAuthorDialogVisible = true; //开启这个编辑的对话框
    },
    editUserAuthorDialogClose() {
      //重复这个操作，也就是讲这个
      this.editUserAuthorDialogVisible = false;
    },
    async editUserAuthor() {
      const authorities = this.author.join(",");
      console.log("==================打印出来这个权限的名称==================");
      console.log(authorities);
      console.log("====================================");
      const { data: res } = await this.$http.post(
        `admin/updateAuthorites?phoneNumber=${this.authorid}&authorities=${authorities}`
      );
      if (res != "200") {
        return this.$message.error("操作失败");
      }
      this.getUserList();
      this.editUserAuthorDialogVisible = false;
      this.$message.success("成功操作！");
    },
    // 更新这个下面的分页条的作用，然后可以在这个地方进行使用。
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUserList();
    },
    handleAddMoreUser() {
      this.$message.error("该操作未完成！");
    },

    //执行这个更新的操作
    async onChangeUserState(userInfo) {
      const { data: res } = await this.$http.post(
        `admin/updateUserState?phoneNumber=${userInfo.phoneNumber}&enable=${userInfo.enable}`
      );
      if (res != "200") {
        userInfo.enable = !userInfo.enable;
        return this.$message.error("操作失败");
      }

      this.$message.success("成功操作！");
    },

    //添加的一个对话框的操作
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      this.addDialogVisible = false;
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.post(
        "admin/getUserByPhoneNum?phoneNumber=" + id
      );
      this.editForm = res; //查询出来的用户信息，反填到这个编辑的表单
      this.editDialogVisible = true; //开启这个编辑的对话框
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
      this.editDialogVisible = false;
    },
    async editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return; //现在是验证成功了！！！
        const { data: res } = await this.$http.post(
          "admin/editUserInfo?" +
            "userName=" +
            this.addForm.userName +
            "&password=" +
            this.addForm.password +
            "&phoneNumber=" +
            this.addForm.phoneNumber +
            "&email=" +
            this.addForm.email +
            "&collage=" +
            this.addForm.collage +
            "&sex=" +
            this.addForm.sex
        );
        if (res != "200") {
          return this.$message.error("更新失败！");
        }
        this.$message.success("更新成功！");
        this.editDialogVisible = false;
        this.getUserList();
      });
    },

    // 添加还有修改的一个User的一个方法
    async addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "admin/addUser?" +
            "userName=" +
            this.addForm.userName +
            "&password=" +
            this.addForm.password +
            "&phoneNumber=" +
            this.addForm.phoneNumber +
            "&email=" +
            this.addForm.email +
            "&collage=" +
            this.addForm.collage +
            "&sex=" +
            this.addForm.sex
        );
        if (res != "200") {
          this.$message.error("操作失败！");
        }
        this.$message.success("操作成功！");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },

    //删除操作
    async deleteUser(phoneNumberId) {
      const confirm = await this.$confirm("是否继续！！！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      if (confirm != "confirm") {
        return this.$message.info("取消删除");
      }
      const { data: res } = await this.$http.delete(
        "admin/deleteUserById?phoneNumber=" + phoneNumberId
      );
      if (res != "200") {
        return this.$message.error("删除失败！");
      }
      this.$message.success("删除成功！");
      this.getUserList();
    },
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 12px;
}

el-dialog {
  width: 200px;
}

.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
  margin-right: 15px;
}

.block {
  margin-top: 10px;
}


</style>
